package boss;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyBlockQueue<E> {
    // 队列容量
    private int size;
    // 存储元素
    LinkedList<E> list = new LinkedList<>();
    // 阻塞 锁
    ReentrantLock lock = new ReentrantLock();

    // 队列满
    Condition full = lock.newCondition();
    // 队列空
    Condition empty = lock.newCondition();

    public MyBlockQueue(){

    }

    public MyBlockQueue(int size){
        this.size = size;
    }

    public void addQueue(E e) throws InterruptedException {
        lock.lock();
        try {
            while (list.size() == size){
                full.await();
            }

            list.add(e);
            System.out.println("入队："+e);
            empty.signal();
        }finally {
            lock.unlock();
        }
    }

    public E deQueue() throws InterruptedException {
        E e;
        lock.lock();
        try{
            while (list.size()==0){
                empty.await();
            }
            e = list.removeFirst();
            System.out.println("出队："+e);
            full.signal();
            return e;
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        MyBlockQueue myBlockQueue = new MyBlockQueue(3);
        new Thread(()->{
            for (int i=0; i<5; i++){
                try {
                    myBlockQueue.addQueue(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(()->{
            for (int i=0; i<5; i++){
                try {
                    myBlockQueue.deQueue();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
